//
//  UploadManager.m
//  ACMediaFrameExample
//
//  Created by 付顺龙 on 2019/3/12.
//  Copyright © 2019 ArthurCao. All rights reserved.
//

#import "UploadManager.h"
#define kSuperUploadBlockSize 1024*1024

@implementation UploadModel
- (void)setUploadedCount:(NSInteger)uploadedCount {
    _uploadedCount = uploadedCount;
    self.uploadPercent = (CGFloat)uploadedCount / self.totalCount;
    self.progressLableText = [NSString stringWithFormat:@"%.2fMB/%.2fMB",self.totalSize * self.uploadPercent /1024.0/1024.0,self.totalSize/1024.0/1024.0];
    if (self.progressBlock) {
        self.progressBlock(self.uploadPercent,self.progressLableText);
    }
}
@end
@interface UploadManager()

@property (nonatomic,strong) NSMutableArray *models;
@end
@implementation UploadManager
#pragma mark- first upload 断点
-(instancetype)init {
    if (self = [super init]) {
        self.models = [NSMutableArray array];
    }
    return self;
}
+(UploadManager *)shareUploadManager {
    static UploadManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [UploadManager new];
    });
    
    return manager;
}

//http://47.95.9.40/vlearn/ClockController/getBreakPointUploadLength
// 上传初始化
- (void)uploadData:(NSData *)data withModel:(UploadModel *)model {
    NSString *token = [UserModel getUserModel].token;
    model.parameters = [NSMutableDictionary dictionary];
    model.upToken = token;//@"38@18911955341@1550471452379";
//    WKUploadFileLength_WKURL
    //@"http://47.95.9.40/vlearn/ClockController/getBreakPointUploadLength"
    model.filePath = [self writeToCacheVideo:data appendNameString:model.lastPathComponent];
    [WYHXNetWorkManager get:WKUploadFileLength_WKURL params:@{@"token":model.upToken,@"fileId":model.filePath.lastPathComponent} completionHandler:^(id responseObj, NSError *error) {
        
        NSInteger offset = [responseObj[@"data"] integerValue];
        NSInteger index = 1;
        if (offset > 0) {
            index = offset/kSuperUploadBlockSize;
            [self sendData:data Model:model Offset:offset DefaultIndex:index];
        }else {
            [self sendData:data Model:model Offset:0 DefaultIndex:index];
        }
    }];
}
- (void)sendData:(NSData *)data Model:(UploadModel *)model Offset:(NSInteger)offset DefaultIndex:(NSInteger)index {
    //token
    NSString *token = [UserModel getUserModel].token;
    // 计算片数
    NSInteger count = data.length / (kSuperUploadBlockSize);
    NSInteger blockCount = data.length % (kSuperUploadBlockSize) == 0 ? count : count + 1;
    // 给model赋值
    model.filePath = [self writeToCacheVideo:data appendNameString:model.lastPathComponent];
    model.totalCount = blockCount;
    model.totalSize = data.length;
    model.uploadedCount = index;
    model.upToken = token;//@"38@18911955341@1550471452379";
    model.isRunning = YES;
    
    // 上传所需参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"offset"] = @(offset);
    
    parameters[@"fileId"] = model.filePath.lastPathComponent;
    parameters[@"token"] = model.upToken;
    NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:model.filePath];
    NSInteger blockSize = kSuperUploadBlockSize;
    
    NSData *blockData = [handle readDataOfLength:blockSize];
    parameters[@"fileLength"] = @(model.totalSize);
    NSString *requestUrl = WKUploadVideo_WKURL;//视频上传接口
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSURLSessionDataTask *dataTask = [manager POST:requestUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
        [formData appendPartWithFileData:blockData name:@"buffer" fileName:model.filePath.lastPathComponent mimeType:@"mp4"];
    } success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
        NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:model.filePath];
        if (handle == nil) { return; }
        [self continueUploadWithModel:model];
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
//        NSLog(@"后台上传失败");
    }];
    model.dataTask = dataTask;
}
#pragma mark- continue upload
- (void)continueUploadWithModel:(UploadModel *)model {
    if (!model.isRunning) {
        return;
    }
    __block NSInteger i = model.uploadedCount;
    

    NSInteger offset = i*kSuperUploadBlockSize;
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"offset"] = @(offset);
    parameters[@"fileLength"] = @(model.totalSize);
    parameters[@"fileId"] = model.filePath.lastPathComponent;
    parameters[@"token"] = model.upToken;
    
    NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:model.filePath];
    [handle seekToFileOffset:offset];
    NSInteger blockSize = kSuperUploadBlockSize;
    NSData *blockData = [handle readDataOfLength:blockSize];
    
    NSString *requestUrl = WKUploadVideo_WKURL;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSURLSessionDataTask *dataTask = [manager POST:requestUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
        [formData appendPartWithFileData:blockData name:@"buffer" fileName:model.filePath.lastPathComponent mimeType:@"mp4"];
    } success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
        i ++;
        model.uploadedCount = i;
        if (i < model.totalCount) {
            [self continueUploadWithModel:model];
        }else {
            if (self.successBlock) {
                //TODO:: 传入filePath  这里后台 返回的数据是 msg
                [model.parameters setObject:responseObject[@"msg"] forKey:@"url"];
                [self saveRequest:model];
            }
        }
//        NSLog(@"%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [self continueUploadWithModel:model];
    }];
    model.dataTask = dataTask;
    //    }];
    
}
#pragma mark- write cache file
- (NSString *)writeToCacheVideo:(NSData *)data appendNameString:(NSString *)name {
    NSString *cachesDirectory = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    NSString *createPath = [cachesDirectory stringByAppendingPathComponent:@"video"];
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    [fileManager createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];
    NSString *path = [cachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/video/%.0f%@",[NSDate date].timeIntervalSince1970,name]];
    [data writeToFile:path atomically:NO];
    return path;
}
- (void)saveRequest:(UploadModel *)model {
    if (self.successBlock) {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSError *err;
        if ([fileManager fileExistsAtPath:model.filePath]) {
            [fileManager removeItemAtPath:model.filePath error:&err];
        }
        self.successBlock(model.parameters[@"url"]);
    }
}
@end
